<template>
  <view class="common-config-container">
    <view class="header">
      <text class="title">常用配置</text>
    </view>
    <!-- 配置内容 -->
    <scroll-view class="config-content" scroll-y>
      <!-- 开门速度 -->
      <view class="config-section">
        <view class="slider-header">
          <text class="section-title">开门速度</text>
          <text class="slider-value">{{
            speedLabels[deviceInfo.openingSpeed - 1]
          }}</text>
        </view>
        <view class="custom-slider-container">
          <!-- 自定义滑块组件 -->
          <view
            id="openingSpeed-slider"
            class="custom-slider"
            @touchstart="handleTouchStart($event, 'openingSpeed', 1, 3)"
            @touchmove="handleTouchMove($event, 'openingSpeed', 1, 3)"
            @touchend="handleTouchEnd"
            @tap="handleClick($event, 'openingSpeed', 1, 3)"
          >
            <!-- 滑块轨道 -->
            <view class="slider-track">
              <!-- 激活部分 -->
              <view
                class="slider-active-track"
                :style="{
                  width: getSliderProgress(deviceInfo.openingSpeed, 1, 3) + '%',
                }"
              ></view>
            </view>
            <!-- 刻度标记 -->
            <view
              v-for="(tick, index) in getTickMarks(1, 3, 1)"
              :key="index"
              class="tick-dot"
              :style="{ left: getTickPosition(tick, 1, 3) }"
            ></view>
            <!-- 滑块手柄 -->
            <view
              class="slider-handle"
              :style="{
                left: getSliderProgress(deviceInfo.openingSpeed, 1, 3) + '%',
              }"
            ></view>
          </view>
          <!-- 标签 -->
          <view class="slider-labels">
            <text
              v-for="(tick, index) in getTickMarks(1, 3, 1)"
              :key="index"
              class="slider-label"
              :style="{ left: getTickPosition(tick, 1, 3) }"
            >
              {{ speedLabels[tick - 1] }}
            </text>
          </view>
        </view>
      </view>

      <!-- 开门保持时间 -->
      <view class="config-section">
        <view class="slider-header">
          <text class="section-title">开门保持时间</text>
          <text class="slider-value">{{ deviceInfo.openingDuration }}s</text>
        </view>
        <view class="custom-slider-container">
          <!-- 自定义滑块组件 -->
          <view
            id="openingDuration-slider"
            class="custom-slider"
            @touchstart="handleTouchStart($event, 'openingDuration', 0, 9)"
            @touchmove="handleTouchMove($event, 'openingDuration', 0, 9)"
            @touchend="handleTouchEnd"
            @tap="handleClick($event, 'openingDuration', 0, 9)"
          >
            <!-- 滑块轨道 -->
            <view class="slider-track">
              <!-- 激活部分 -->
              <view
                class="slider-active-track"
                :style="{
                  width:
                    getSliderProgress(deviceInfo.openingDuration, 0, 9) + '%',
                }"
              ></view>
            </view>
            <!-- 刻度标记 -->
            <view
              v-for="(tick, index) in getTickMarks(0, 9, 1)"
              :key="index"
              class="tick-dot"
              :style="{ left: getTickPosition(tick, 0, 9) }"
            ></view>
            <!-- 滑块手柄 -->
            <view
              class="slider-handle"
              :style="{
                left: getSliderProgress(deviceInfo.openingDuration, 0, 9) + '%',
              }"
            ></view>
          </view>
          <!-- 标签 -->
          <view class="slider-labels">
            <text
              v-for="(tick, index) in getTickMarks(0, 9, 1)"
              :key="index"
              class="slider-label"
              :style="{ left: getTickPosition(tick, 0, 9) }"
            >
              {{ tick }}s
            </text>
          </view>
        </view>
      </view>

      <!-- 开门角度 -->
      <view class="config-section">
        <view class="slider-header">
          <text class="section-title">开门角度</text>
          <text class="slider-value">{{ deviceInfo.openingAngle * 10 }}°</text>
        </view>
        <view class="custom-slider-container">
          <!-- 自定义滑块组件 -->
          <view
            id="openingAngle-slider"
            class="custom-slider"
            @touchstart="handleTouchStart($event, 'openingAngle', 7, 18)"
            @touchmove="handleTouchMove($event, 'openingAngle', 7, 18)"
            @touchend="handleTouchEnd"
            @tap="handleClick($event, 'openingAngle', 7, 18)"
          >
            <!-- 滑块轨道 -->
            <view class="slider-track">
              <!-- 激活部分 -->
              <view
                class="slider-active-track"
                :style="{
                  width:
                    getSliderProgress(deviceInfo.openingAngle, 7, 18) + '%',
                }"
              ></view>
            </view>
            <!-- 刻度标记 -->
            <view
              v-for="(tick, index) in getTickMarks(7, 18, 1)"
              :key="index"
              class="tick-dot"
              :style="{ left: getTickPosition(tick, 7, 18) }"
            ></view>
            <!-- 滑块手柄 -->
            <view
              class="slider-handle"
              :style="{
                left: getSliderProgress(deviceInfo.openingAngle, 7, 18) + '%',
              }"
            ></view>
          </view>
          <!-- 标签 -->
          <view class="slider-labels">
            <text
              v-for="(tick, index) in getTickMarks(7, 18, 1)"
              :key="index"
              class="slider-label"
              :style="{ left: getTickPosition(tick, 7, 18) }"
            >
              {{ tick * 10 }}°
            </text>
          </view>
        </view>
      </view>

      <!-- 关门速度 -->
      <view class="config-section">
        <view class="slider-header">
          <text class="section-title">关门速度</text>
          <text class="slider-value">{{
            speedLabels[deviceInfo.closingSpeed - 1]
          }}</text>
        </view>
        <view class="custom-slider-container">
          <!-- 自定义滑块组件 -->
          <view
            id="closingSpeed-slider"
            class="custom-slider"
            @touchstart="handleTouchStart($event, 'closingSpeed', 1, 3)"
            @touchmove="handleTouchMove($event, 'closingSpeed', 1, 3)"
            @touchend="handleTouchEnd"
            @tap="handleClick($event, 'closingSpeed', 1, 3)"
          >
            <!-- 滑块轨道 -->
            <view class="slider-track">
              <!-- 激活部分 -->
              <view
                class="slider-active-track"
                :style="{
                  width: getSliderProgress(deviceInfo.closingSpeed, 1, 3) + '%',
                }"
              ></view>
            </view>
            <!-- 刻度标记 -->
            <view
              v-for="(tick, index) in getTickMarks(1, 3, 1)"
              :key="index"
              class="tick-dot"
              :style="{ left: getTickPosition(tick, 1, 3) }"
            ></view>
            <!-- 滑块手柄 -->
            <view
              class="slider-handle"
              :style="{
                left: getSliderProgress(deviceInfo.closingSpeed, 1, 3) + '%',
              }"
            ></view>
          </view>
          <!-- 标签 -->
          <view class="slider-labels">
            <text
              v-for="(tick, index) in getTickMarks(1, 3, 1)"
              :key="index"
              class="slider-label"
              :style="{ left: getTickPosition(tick, 1, 3) }"
            >
              {{ speedLabels[tick - 1] }}
            </text>
          </view>
        </view>
      </view>

      <!-- 人体感应灵敏度 -->
      <view class="config-section">
        <view class="slider-header">
          <text class="section-title">人体感应灵敏度</text>
          <text class="slider-value">{{
            motionSensitivityLabels[deviceInfo.motionSensitivity]
          }}</text>
        </view>
        <view class="custom-slider-container">
          <!-- 自定义滑块组件 -->
          <view
            id="motionSensitivity-slider"
            class="custom-slider"
            @touchstart="handleTouchStart($event, 'motionSensitivity', 0, 3)"
            @touchmove="handleTouchMove($event, 'motionSensitivity', 0, 3)"
            @touchend="handleTouchEnd"
            @tap="handleClick($event, 'motionSensitivity', 0, 3)"
          >
            <!-- 滑块轨道 -->
            <view class="slider-track">
              <!-- 激活部分 -->
              <view
                class="slider-active-track"
                :style="{
                  width:
                    getSliderProgress(deviceInfo.motionSensitivity, 0, 3) + '%',
                }"
              ></view>
            </view>
            <!-- 刻度标记 -->
            <view
              v-for="(tick, index) in getTickMarks(0, 3, 1)"
              :key="index"
              class="tick-dot"
              :style="{ left: getTickPosition(tick, 0, 3) }"
            ></view>
            <!-- 滑块手柄 -->
            <view
              class="slider-handle"
              :style="{
                left:
                  getSliderProgress(deviceInfo.motionSensitivity, 0, 3) + '%',
              }"
            ></view>
          </view>
          <!-- 标签 -->
          <view class="slider-labels">
            <text
              v-for="(tick, index) in getTickMarks(0, 3, 1)"
              :key="index"
              class="slider-label"
              :style="{ left: getTickPosition(tick, 0, 3) }"
            >
              {{ motionSensitivityLabels[tick] }}
            </text>
          </view>
        </view>
      </view>

      <!-- 防夹灵敏度 -->
      <view class="config-section">
        <view class="slider-header">
          <text class="section-title">防夹灵敏度</text>
          <text class="slider-value">{{
            deviceInfo.antiPinchSensitivity
          }}</text>
        </view>
        <view class="custom-slider-container">
          <!-- 自定义滑块组件 -->
          <view
            id="antiPinchSensitivity-slider"
            class="custom-slider"
            @touchstart="handleTouchStart($event, 'antiPinchSensitivity', 0, 9)"
            @touchmove="handleTouchMove($event, 'antiPinchSensitivity', 0, 9)"
            @touchend="handleTouchEnd"
            @tap="handleClick($event, 'antiPinchSensitivity', 0, 9)"
          >
            <!-- 滑块轨道 -->
            <view class="slider-track">
              <!-- 激活部分 -->
              <view
                class="slider-active-track"
                :style="{
                  width:
                    getSliderProgress(deviceInfo.antiPinchSensitivity, 0, 9) +
                    '%',
                }"
              ></view>
            </view>
            <!-- 刻度标记 -->
            <view
              v-for="(tick, index) in getTickMarks(0, 9, 1)"
              :key="index"
              class="tick-dot"
              :style="{ left: getTickPosition(tick, 0, 9) }"
            ></view>
            <!-- 滑块手柄 -->
            <view
              class="slider-handle"
              :style="{
                left:
                  getSliderProgress(deviceInfo.antiPinchSensitivity, 0, 9) +
                  '%',
              }"
            ></view>
          </view>
          <!-- 标签 -->
          <view class="slider-labels">
            <text
              v-for="(tick, index) in getTickMarks(0, 9, 1)"
              :key="index"
              class="slider-label"
              :style="{ left: getTickPosition(tick, 0, 9) }"
            >
              {{ tick }}
            </text>
          </view>
        </view>
        <text class="note">备注：数值越大，灵敏度越高</text>
      </view>

      <!-- 常开门设置 -->
      <view class="config-section">
        <view class="toggle-section">
          <text class="section-title" style="margin-bottom: 0">常开门设置</text>
          <view class="toggle-container">
            <text
              class="toggle-status"
              :class="{ active: deviceInfo.alwaysOpen }"
            >
              {{ deviceInfo.alwaysOpen ? "开启" : "关闭" }}
            </text>
            <switch
              :checked="deviceInfo.alwaysOpen"
              @change="handleSwitchChange($event, 'alwaysOpen')"
              color="#2c3045"
              class="toggle-switch"
            />
          </view>
        </view>
      </view>

      <!-- 底部间距，为固定按钮留出空间 -->
      <view class="bottom-spacer"></view>
    </scroll-view>

    <!-- 固定在底部的操作按钮 -->
    <view class="action-buttons">
      <button class="action-btn open-btn" @click="handleDoorAction('open')">
        <text class="btn-text">开门</text>
      </button>
      <button class="action-btn close-btn" @click="handleDoorAction('close')">
        <text class="btn-text">关门</text>
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, reactive } from "vue";
import { bluetoothManager, buildPacket } from "@/utils";
const deviceInfo = reactive({
  openingSpeed: 1,
  openingDuration: 3,
  openingAngle: 90,
  closingSpeed: 1,
  motionSensitivity: 1,
  antiPinchSensitivity: 5,
  alwaysOpen: false,
});
onMounted(() => {
  const currentDeviceInfo = uni.getStorageSync("deviceInfo");
  const content = currentDeviceInfo.slice(8).match(/.{1,2}/g) ?? [];
  const [
    openingSpeedValue,
    openingDurationValue,
    openingAngleValue,
    closingSpeedValue,
    motionSensitivityValue,
    antiPinchSensitivityValue,
    alwaysOpenValue,
  ] = content;
  console.log("content", content);
  deviceInfo.openingSpeed = +openingSpeedValue;
  deviceInfo.openingDuration = +openingDurationValue;
  deviceInfo.openingAngle = parseInt(openingAngleValue, 16);
  deviceInfo.closingSpeed = +closingSpeedValue;
  deviceInfo.motionSensitivity = +motionSensitivityValue;
  deviceInfo.antiPinchSensitivity = +antiPinchSensitivityValue;
  deviceInfo.alwaysOpen = alwaysOpenValue === "00" ? false : true;
});

const speedLabels = ["低", "中", "高"];
const motionSensitivityLabels = ["关闭", "低", "中", "高"];

// 角度选项 (70, 80, ..., 180)
const angleOptions = Array.from({ length: 12 }, (_, i) => 70 + i * 10);

const angleSliderValue = computed(() => {
  return angleOptions.indexOf(deviceInfo.openingAngle);
});

// 生成刻度标记的函数
const getTickMarks = (min: number, max: number, step: number) => {
  const marks = [];
  for (let i = min; i <= max; i += step) {
    marks.push(i);
  }
  return marks;
};

// 计算刻度位置的函数
const getTickPosition = (value: number, min: number, max: number) => {
  const percentage = ((value - min) / (max - min)) * 100;
  return `${percentage}%`;
};

// 计算滑块进度的函数
const getSliderProgress = (value: number, min: number, max: number) => {
  return ((value - min) / (max - min)) * 100;
};

// 触摸相关变量
let isDragging = false;
let currentField = "";
let currentMin = 0;
let currentMax = 0;

// 处理触摸开始
const handleTouchStart = (e: any, field: string, min: number, max: number) => {
  e.preventDefault();
  isDragging = true;
  currentField = field;
  currentMin = min;
  currentMax = max;
  handleTouchMove(e, field, min, max);
};

// 处理触摸移动
const handleTouchMove = (e: any, field: string, min: number, max: number) => {
  if (!isDragging) return;

  const touch = e.touches[0];
  
  // 使用特定ID选择器获取元素位置
  uni.createSelectorQuery().select(`#${field}-slider`).boundingClientRect((rect: any) => {
    if (rect) {
      processTouch(touch, rect, field, min, max);
    }
  }).exec();
};

// 处理触摸计算
const processTouch = (touch: any, rect: any, field: string, min: number, max: number, shouldSend: boolean = false) => {
  // 计算相对位置
  const x = touch.clientX - rect.left;
  const percentage = Math.max(0, Math.min(100, (x / rect.width) * 100));

  // 根据步长计算精确值
  const range = max - min;
  const steps = range; // 每个单位为一步
  const stepSize = 100 / steps;
  const stepIndex = Math.round(percentage / stepSize);
  const value = min + stepIndex;

  // 确保值在有效范围内
  const clampedValue = Math.max(min, Math.min(max, value));
  
  // 只有值发生变化时才更新
  if ((deviceInfo as any)[field] !== clampedValue) {
    console.log(`更新 ${field}: ${(deviceInfo as any)[field]} -> ${clampedValue}`);
    (deviceInfo as any)[field] = clampedValue;
    
    // 只有在指定时才发送配置更新
    if (shouldSend) {
      debounce(
        field,
        () => {
          sendConfigUpdate();
        },
        100
      );
    }
  }
};

// 处理触摸结束
const handleTouchEnd = () => {
  if (isDragging && currentField) {
    // 在拖拽结束时发送配置更新
    console.log(`拖拽结束，发送 ${currentField} 配置更新`);
    debounce(
      currentField,
      () => {
        sendConfigUpdate();
      },
      100
    );
  }
  
  isDragging = false;
  currentField = "";
};

// 处理点击事件
const handleClick = (e: any, field: string, min: number, max: number) => {
  // 防止在拖拽过程中触发点击
  if (isDragging) return;
  
  console.log(`点击事件触发: ${field}`, e);
  
  // 获取点击位置
  const touch = {
    clientX: e.detail?.x || e.touches?.[0]?.clientX || e.clientX,
    clientY: e.detail?.y || e.touches?.[0]?.clientY || e.clientY
  };
  
  console.log(`点击坐标:`, touch);
  
  uni.createSelectorQuery().select(`#${field}-slider`).boundingClientRect((rect: any) => {
    if (rect) {
      console.log(`滑块位置:`, rect);
      processTouch(touch, rect, field, min, max, true); // 点击时立即发送更新
    }
  }).exec();
};

// 发送配置更新
const sendConfigUpdate = () => {
  uni.showLoading({
    mask: true,
    title: "发送中...",
  });

  const values = Object.values(deviceInfo) as number[];
  values[values.length - 1] = deviceInfo.alwaysOpen ? 0x01 : 0x00;
  const packet = buildPacket(0x03, values);

  bluetoothManager.sendPacket(
    bluetoothManager.serviceId,
    bluetoothManager.characteristicId,
    packet
  );
};

// 处理开关变化
const handleSwitchChange = (e: any, field: string) => {
  (deviceInfo as any)[field] = e.detail.value;
  debounce(
    field,
    () => {
      sendConfigUpdate();
    },
    100
  );
};

// 防抖工具函数
const debounceTimers = new Map<string, number>();

const debounce = (key: string, callback: () => void, delay: number = 300) => {
  // 清除之前的定时器
  if (debounceTimers.has(key)) {
    clearTimeout(debounceTimers.get(key)!);
  }

  // 设置新的定时器
  const timerId = setTimeout(() => {
    callback();
    debounceTimers.delete(key);
  }, delay);

  debounceTimers.set(key, timerId);
};

// 清理所有定时器
const clearAllDebounceTimers = () => {
  debounceTimers.forEach((timerId) => {
    clearTimeout(timerId);
  });
  debounceTimers.clear();
};

const handleDoorAction = (action: string) => {
  uni.showLoading({
    mask: true,
    title: "发送中...",
  });
  const values = Object.values(deviceInfo) as number[];
  values[values.length - 1] = deviceInfo.alwaysOpen ? 0x01 : 0x00;
  if (action === "open") {
    values.push(0x01);
  } else {
    values.push(0x00, 0x01);
  }
  const packet = buildPacket(0x03, values);

  bluetoothManager.sendPacket(
    bluetoothManager.serviceId,
    bluetoothManager.characteristicId,
    packet
  );
};

// 组件卸载时清理定时器
onUnmounted(() => {
  clearAllDebounceTimers();
});
</script>

<style scoped>
.common-config-container {
  height: 100vh;
  min-height: 100vh;
  background: linear-gradient(to bottom, #e6ebff, #f8faff, #ffffff);
  display: flex;
  flex-direction: column;
  width: 100%;
  max-width: 750rpx;
  margin: 0 auto;
  box-sizing: border-box;
  padding-top: calc(env(safe-area-inset-top) + 24rpx);
  padding-bottom: calc(env(safe-area-inset-bottom) + 24rpx);
  padding-left: calc(env(safe-area-inset-left));
  padding-right: calc(env(safe-area-inset-right));
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 24rpx;
  padding-left: 24rpx;
}

.back-btn {
  background: none;
  border: none;
  padding: 16rpx;
  color: #2c3045;
  font-size: 40rpx;
  transition: color 0.3s ease;
}

.back-btn:hover {
  color: #666;
}

.back-icon {
  font-size: 40rpx;
}

.header-center {
  text-align: center;
}

.title {
  color: #2c3045;
  font-size: 32rpx;
  font-weight: bold;
  display: block;
}

.device-name {
  color: #666;
  font-size: 24rpx;
  display: block;
  margin-top: 8rpx;
}

.placeholder {
  width: 80rpx;
}

.config-content {
  flex: 1;
  padding: 24rpx;
  box-sizing: border-box;
}

.config-section {
  background-color: #ecedf4;
  padding: 24rpx;
  border-radius: 16rpx;
  margin-bottom: 72rpx;
  width: 100%;
  box-sizing: border-box;
}

.section-title {
  color: #2c3045;
  font-size: 28rpx;
  font-weight: 500;
  margin-bottom: 20rpx;
  display: block;
}

.slider-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.slider-value {
  color: #2c3045;
  font-size: 24rpx;
  font-weight: 500;
}

/* 自定义滑块容器 */
.custom-slider-container {
  position: relative;
  margin-bottom: 12rpx;
}

/* 自定义滑块主体 */
.custom-slider {
  position: relative;
  height: 40rpx;
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

/* 滑块轨道 */
.slider-track {
  position: absolute;
  left: 0;
  right: 0;
  height: 4rpx;
  background-color: #ddd;
  border-radius: 2rpx;
  top: 50%;
  transform: translateY(-50%);
}

/* 激活轨道 */
.slider-active-track {
  height: 100%;
  background-color: #2c3045;
  border-radius: 2rpx;
  transition: width 0.1s ease;
}

/* 刻度点 */
.tick-dot {
  position: absolute;
  width: 8rpx;
  height: 8rpx;
  background-color: #999;
  border-radius: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  z-index: 2;
}

/* 滑块手柄 */
.slider-handle {
  position: absolute;
  width: 24rpx;
  height: 24rpx;
  background-color: #2c3045;
  border-radius: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  z-index: 3;
  box-shadow: 0 2rpx 8rpx rgba(44, 48, 69, 0.3);
  transition: transform 0.1s ease;
}

.slider-handle:active {
  transform: translate(-50%, -50%) scale(1.2);
}

/* 标签容器 */
.slider-labels {
  position: relative;
  height: 30rpx;
  margin-top: 8rpx;
}

/* 标签样式 */
.slider-label {
  position: absolute;
  font-size: 18rpx;
  color: #666;
  text-align: center;
  transform: translateX(-50%);
  white-space: nowrap;
  top: 0;
}

.note {
  font-size: 22rpx;
  color: #2c3045;
  font-weight: 500;
  margin-top: 12rpx;
  display: block;
}

.toggle-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.toggle-container {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.toggle-status {
  font-size: 24rpx;
  font-weight: 500;
  color: #666;
}

.toggle-status.active {
  color: #2c3045;
}

.toggle-switch {
  transform: scale(1);
}

.bottom-spacer {
  height: calc(120rpx + env(safe-area-inset-bottom));
}

.action-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: white;
  padding: 20rpx;
  border-top: 1rpx solid #f0f0f0;
  display: flex;
  gap: 16rpx;
  max-width: 750rpx;
  margin: 0 auto;
  box-sizing: border-box;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  padding-left: calc(20rpx + env(safe-area-inset-left));
  padding-right: calc(20rpx + env(safe-area-inset-right));
  z-index: 1000;
}

.action-btn {
  flex: 1;
  padding: 16rpx 24rpx;
  border-radius: 16rpx;
  font-size: 28rpx;
  font-weight: 500;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
}

.open-btn {
  background-color: #2c3045;
  color: white;
}

.close-btn {
  background-color: #ecedf4;
  color: #2c3045;
}

.btn-icon {
  font-size: 28rpx;
}

.btn-text {
  font-size: 24rpx;
}
</style>
